
import React from 'react';
import { Card, message, Form, Checkbox, Select as FormilySelect, Button, DatePicker, Row, Col } from 'antd';
import type { FC } from 'react';
import useStyles from './style.style';
import { FormButtonGroup, FormGrid, FormItem, Input, Reset, Select, Space, Submit } from '@formily/antd-v5'
import { createForm } from '@formily/core'
import { createSchemaField, FormProvider } from '@formily/react'
import { dictionaryWhether, getFormattedDate, professionalTypeList, invoiceTypeList, salesTypeList, invoiceTypeOptions, specialTicketTypeOptions, drawerList, reviewerList, payeeList, paymentTypeOptions, taxCalculationOptions, departmentOptions } from './businessFinance';
import FormTable, { FormTableColumn, FormTableRef } from './component/editbusinessFinanceTableConfi';
import InvoiceFormModal, { InvoiceFormModalRef } from './component/InvoiceFormModal';
import columns from './confing';
import { FormTableItem } from './FormTableType';
import { businessFinanceSubmitForm } from '@/../api/businessFinance/service';
const SchemaField = createSchemaField({
  components: {
    Input,
    FormItem,
    Select,
    Space,
    FormGrid,
  },
})
const formItemLayout = {
  labelCol: 6,
};
const businessFinance: FC = () => {
  const { styles } = useStyles();
  // 使用FormTable组件提供的FormTableRef类型
  const childTablseRef = React.useRef<FormTableRef<FormTableItem>>(null);
  // 创建InvoiceFormModal的ref
  const invoiceModalRef = React.useRef<InvoiceFormModalRef>(null);
  // 触发显示发票模态框
  const handleShowInvoiceModal = () => {
    invoiceModalRef.current?.showModal();
    console.log('触发');
  };

  const invoiceForm = createForm<BusinessFinanceFormValues>({
    initialValues: {
      approvalNo: 'BJ-KP-202310-000001', // 开票审批单号初始值
      handler: '张三', // 经办人初始值
      invoiceType: '',
      department: '销售部', // 其他字段初始值
      applyDate: getFormattedDate(),

    },

  })
  // Define the type for invoiceForm values (replace fields with actual ones as needed)
  // 初始数据
  const initialData: DepartmentItem[] = [
    {
      lineNumber: 1, billingDepartment: 'dept1', amount: '1000', isActive: true, remark: '正常单据',
      taxCode: '',
      productInvoiceDetailsList: [],
      CustomerName: '',
      invoiceType: '',
      specialTicketType: ''
    },
    {
      lineNumber: 2, billingDepartment: 'dept2', amount: '2000', isActive: false, remark: '待审核',
      taxCode: '',
      productInvoiceDetailsList: [],
      CustomerName: '',
      invoiceType: '',
      specialTicketType: ''
    },
  ];
  // 提交方法
  const onFinish = async () => {
    // const isValid = await childTablseRef.current?.validateFields()
    // if (!isValid) {
    //   return;
    // }
    let pathValues = invoiceForm.values;
    console.log(pathValues, '表单数据');


    const res = await businessFinanceSubmitForm(pathValues)
    if (res.code === 200) {
      message.success('提交成功');
    } else {
      message.error(res.message);
    }
  };
  // 处理表单提交
  const handleFinishText = async () => {
    console.log('提交的数据:', childTablseRef.current?.getTableData());
    // 校验方法
    const isValid = await childTablseRef.current?.validateFields()
    if (!isValid) {

      return;
    }
    // 这里可以添加API调用等逻辑

  };

  // 销售方名称选中回调
  const handleChildAction = (value: GithubIssueItem[]) => {
    console.log('子组件触发了父组件方法', value);

    const item = value[0]

    invoiceForm.initialValues.invoiceNumber = item.invoiceNumber
    invoiceForm.initialValues.invoiceDocumentNumber = item.invoiceDocumentNumber
    invoiceForm.initialValues.invoiceAmount = item.invoiceAmount
    invoiceForm.initialValues.isControlInvoicing = item.isControlInvoicing
    invoiceForm.initialValues.sellerAccount = item.sellerAccount
    invoiceForm.initialValues.sellerName = item.title
  };
  return (
    <>
      <FormProvider form={invoiceForm}>
        <div style={{
          backgroundColor: '#ffffff', // 白色背景
          padding: '24px', // 内边距
          borderRadius: '8px', // 圆角
          boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)', // 轻微阴影，增强层次感

        }}>
          <div style={{ display: 'flex', height: '40px', marginBottom: '40px', justifyContent: "space-between" }}>
            <div></div>
            <FormButtonGroup>
              <div onClick={handleFinishText}>测试</div>
              <Reset>重置</Reset>
              <Submit onSubmit={onFinish}>提交</Submit>
            </FormButtonGroup>
          </div>
          <SchemaField>
            <SchemaField.Void
              x-component="FormGrid"
              x-component-props={{
                maxColumns: 3,
                minColumns: 2,
              }}
            >
              <SchemaField.String name="approvalNo" x-component="Input" title="开票审批单号" x-decorator="FormItem" x-decorator-props={formItemLayout} x-component-props={{ placeholder: "自动生成 分公司代码+KP/TP+年月+六位" }} />
              <SchemaField.String name="handler" title="经办人" x-decorator="FormItem" x-component="Input" x-decorator-props={formItemLayout} x-component-props={{ disabled: true }} />
              <SchemaField.String name="department" title="经办部门" x-decorator="FormItem" x-component="Input" x-decorator-props={formItemLayout} x-component-props={{ disabled: true }} />
              <SchemaField.String name="childBranch" title="经办分公司" x-decorator="FormItem" x-component="Input" x-decorator-props={formItemLayout} x-component-props={{ disabled: true }} />
              <SchemaField.String name="applyDate" title="经办日期" x-decorator="FormItem" x-component="Input" x-decorator-props={formItemLayout} x-component-props={{ disabled: true }} />
              <SchemaField.String name="sellerName" title="销售方名称" required x-decorator="FormItem" x-decorator-props={formItemLayout} x-component={({ value, onChange }) => (
                <Row gutter={8} align="middle">
                  <Col flex={1}>
                    <Input disabled value={value} onChange={onChange} />
                  </Col>
                  <Col>
                    <Button type="primary" onClick={handleShowInvoiceModal} >选择</Button>
                  </Col>
                </Row>
              )}
              />
              <SchemaField.String name="sellerAccount" title="销售方开户行及账号" x-decorator="FormItem" x-component="Input" x-decorator-props={formItemLayout} x-disabled={true} />
              <SchemaField.String name="invoiceType" enum={invoiceTypeList} required title="开票类型" x-decorator="FormItem" x-component="Select" x-component-props={{ allowClear: true, style: { width: "100%", }, }} x-decorator-props={formItemLayout} />
              <SchemaField.String name="invoiceNumber" title="原发票号" x-decorator="FormItem" x-component="Input" x-decorator-props={formItemLayout} x-disabled={true} />
              <SchemaField.String name="invoiceDocumentNumber" title="原发票单据号" x-decorator="FormItem" x-component="Input" x-decorator-props={formItemLayout} x-disabled={true} />
              <SchemaField.String name="invoiceAmount" title="原发票金额" x-decorator="FormItem" x-component="Input" x-decorator-props={formItemLayout} x-disabled={true} />
              <SchemaField.String name="isControlInvoicing" title="是否传税控开票" x-decorator="FormItem" x-component="Input" x-decorator-props={formItemLayout} x-disabled={true} />
              <SchemaField.String name="salesType" title="销售类型" x-decorator="FormItem" enum={salesTypeList} x-component="Select" x-decorator-props={formItemLayout} />
              <SchemaField.String name="isreceived" title="是否确收" enum={dictionaryWhether} x-decorator="FormItem" x-component="Select" x-decorator-props={formItemLayout} />
              <SchemaField.String name="reversalReason" title="红冲原因" x-decorator="FormItem" x-component="Input.TextArea" x-decorator-props={formItemLayout} x-visible={false}
                x-reactions={[
                  {
                    dependencies: ['invoiceType'],
                    fulfill: {
                      state: {
                        visible: "{{$deps[0] === 'HC'}}"
                      }
                    }
                  }
                ]}
              />
              <SchemaField.String name="voidReason" title="作废原因" x-decorator="FormItem" x-component="Input.TextArea" x-decorator-props={formItemLayout} x-visible={false}
                x-reactions={[
                  {
                    dependencies: ['invoiceType'],
                    fulfill: {
                      state: {
                        visible: "{{$deps[0] === 'ZF'}}"
                      }
                    }
                  }
                ]} />
              <SchemaField.String name="professionaltype" title="专业类型" x-decorator="FormItem" enum={professionalTypeList} x-component="Select" x-decorator-props={formItemLayout} />
            </SchemaField.Void>
          </SchemaField>
        </div>
      </FormProvider>
      <div style={{ height: '30px' }}></div>

      <FormTable
        initialData={initialData}
        columns={columns}
        ref={childTablseRef}
        onFinish={handleFinishText}
        submitText="保存费用数据"
        showReset={true}
        showAdd={true}
        formProps={{
          layout: 'vertical'
        }}
        tableProps={{
          scroll: { x: 1000 }
        }}
        className={styles.noMarginBottom}
      />


      <InvoiceFormModal ref={invoiceModalRef} selectionType="radio" onSelectedEvent={handleChildAction} />
    </>
  );
};
export default businessFinance;
